<template>
  <div :class="{ hideUpload: limit == uploadFileList.length }">
    <el-upload
      ref="upload"
      v-loading="uploading"
      action=""
      list-type="picture-card"
      :limit="limit"
      :file-list="uploadFileList"
      :disabled="disable"
      :http-request="params => handleFile(params)" 
      :on-remove="handleRemove"
    >
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{file}">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
      </div>
    </el-upload>
    <el-dialog :close-on-click-modal='false' :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import DocumentApi from "@/api/document"
import config from '@/api/config'
export default {
  components: {},
  props: {
    urlList: {
      type: Array,
      default: () => ([])
    },
    disabled: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: null
    },
  },
  data () {
    return {
      uploadFileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      disable: false,
      uploading: false,
    };
  },
  watch: {
    urlList (val) {
      console.log(val)
      this.uploadFileList = val
    },
    disabled (val) {
      this.disable = val
    },
  },
  mounted () {
    this.uploadFileList = this.urlList
    this.disable = this.disabled
  },
  methods: {
    handleRemove (file) {
      var index = this.uploadFileList.findIndex(a => a.name === file.name)
      if (index !== -1) {
        this.uploadFileList.splice(index, 1);
        this.getFile()
      }
    },
    // 上传文件
    handleFile (files) {
      let { file } = files
      let dataForm = new FormData()
      dataForm.append('file', file)
      dataForm.append('moduleType', 'SCIENCE_PRODUCT')
      this.uploading = true
      DocumentApi.getUploadUrl(dataForm).then(res => {
        let filePath = res.data
        let url = config.webServiceUrl + filePath
        this.uploadFileList.push({ url, name: url })
        this.getFile()
        this.uploading = false
      }).catch(() => {
        this.uploading = false
        this.$message.error('上传图片失败！')
      })
    },
    getFile() {
      this.$emit('getFile', this.uploadFileList)
    },
    clearFile() {
      this.$refs.upload && this.$refs.upload.clearFiles()
    }
  }
};
</script>

<style lang="scss" scoped>
.hideUpload {
  ::v-deep .el-upload{
    display: none;
  }
}
</style>
